package de.homelabs.hlmodules.cms.menu.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import de.homelabs.hlmodules.cms.api.menu.service.IHLMenuManager;
import de.homelabs.hlmodules.cms.content.service.HLPageManager;
import de.homelabs.hlmodules.cms.menu.domain.HLMenuEntry;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Service("hlMenuManager")
public class HLMenuManager implements IHLMenuManager {

	@Autowired
	HLPageManager hlPageManager;
	
	@Autowired
	FreeMarkerConfigurer freemarkerConfig;
	
	public StringBuffer getMainMenu() {
		StringBuffer mainMenu = new StringBuffer();
		
		//Menu ueber alle Seiten erstellen
		Map<String, String> pageList = hlPageManager.getPageList();
		
		//try to load menuTemaplate
		try {
			//try to load Template
			Configuration cfg = freemarkerConfig.getConfiguration();
			Template template = cfg.getTemplate("menutemplate.html");
			
			//seems we have a Template
			Map<String, Object> model = new HashMap<String, Object>();
			List<HLMenuEntry> entryList = new ArrayList<HLMenuEntry>();
			
			//Loop over Page items
			for (String value : pageList.values()){
				HLMenuEntry menuEntry = new HLMenuEntry();
				menuEntry.setMenuLink(value+".htm");
				menuEntry.setMenuText(value);
				//add to List
				entryList.add(menuEntry);
			}
			
			//add to Model
			model.put("menuEntries", entryList);
			
			//parse menu
			return new StringBuffer(
					FreeMarkerTemplateUtils
						.processTemplateIntoString(template, model));
		} catch (IOException e){
			System.out.println(e.getLocalizedMessage());
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//default menu
		if (pageList != null){
			//build mainmenu
			mainMenu.append("<ul id='mainmenu'>");
		for (String value : pageList.values()){
		    	mainMenu.append("<li><a href='"+value
		    			+".htm'>"+value
		    			+"</a></li>");
		    }
		    mainMenu.append("</ul>");
		    return mainMenu;
		} 
		
		//kein menu
		return null;
	}

}
